import logging
import pymysql
from django.http import JsonResponse

from comment.comservice import add_filter
from comment.comviews import com_views, success_response, err_response, format_response
from utils.dbutils import PymysqlUtil, DB_Config, MysqlTools
from utils.formatutils import get_params
from utils.pageutils import paging_simple
from .sqlmap import *
from django.db import connection

mysql_tools = MysqlTools(db_config=DB_Config.get("default"))
project_status = {1: "进场交接", 2: "合同", 3: "招投标", 4: "投资核算", 5: "确定意向", 6: "挂起"}
project_type = {1: "运营", 2: "设计", 3: "投资", 4: "工程改造", 5:"承包"}


def my_project_message(params):
    dict = {
        "user_id": "user_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if not val:
    #         return err_response(210)
    sql = ProjectSqlMap.MESSAGE_LIST + " inner join aoa_user as t6 on t1.dept_id=t6.dept_id where t6.user_id={user_id}"
    sql = sql.format(**params)
    result = mysql_tools.select_one(sql)
    if not result:
        return success_response({})
    project_status_id = result.get("project_state")
    project_type_id = result.get("project_type")
    if not project_status_id:
        result["status_name"] = None
    else:
        result["status_name"] = project_status.get(project_status_id)
    result["floor_space"] = str(result.get("floor_space")) + "平方米"

    if not project_type_id:
        result["type_name"] = None
    else:
        result["type_name"] = project_status.get(project_type_id)
    return success_response(result)


def project_message(params):
    dict = {
        "project_id": "project_id"
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if not val:
    #         return err_response(210)
    sql = ProjectSqlMap.MESSAGE_LIST + " where t1.project_id={project_id}"
    sql = sql.format(**params)
    result = mysql_tools.select_one(sql)
    if not result:
        return success_response({})
    result["status_name"] = project_status.get(result.get("project_state"))
    result["type_name"] = project_type.get(result.get("project_type"))
    result["floor_space"] = str(result.get("floor_space")) + "平方米"
    return success_response(result)


def project_task(params):
    dict = {
        "project_id": "project_id"
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "status_id": "status_id",
        "query_str_task": "query_str"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # if not params["project_id"]:
    #     return err_response(210)
    sql = add_filter(ProjectSqlMap.project_task_all, params, ["status_id", "query_str_task"],
                     **ProjectSqlMap.FILTER_PARAMS)
    sql += " order by t1.publish_time desc"
    sql = sql.format(**params)
    result = mysql_tools.select_all(sql)
    if params.get("isall") != 1:
        if isinstance(result,JsonResponse):
            return result
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        if res.get("star_time"):
            res["star_time"] = str(res.get("star_time"))
        else:
            res["star_time"] = None
        if res.get("end_time"):
            res["end_time"] = str(res.get("end_time"))
        else:
            res["end_time"] = None
        if res.get("progress_speed"):
            res["progress_speed"] = str(int(res.get("progress_speed") * 100)) + "%"
        else:
            res["progress_speed"] = None
        if res["priority_level"] == 0:
            res["priority_level_name"] = "低"
        elif res["priority_level"] == 1:
            res["priority_level_name"] = "中"
        else:
            res["priority_level_name"] = "高"
    return success_response(result)


# def project_task_add(params):
#     dict = {
#         "title": "title",
#         "task_describe": "task_describe",
#         "star_time": "star_time",
#         "end_time": "end_time",
#         "reciverlist_id": "reciverlist_id",
#         "task_push_user_id": "task_push_user_id",
#         "task_project_id": "task_project_id"
#     }
#     params = get_params(params, dict)
#     if isinstance(params, JsonResponse):
#         return params
#     for key, val in params.items():
#         if val is None:
#             return err_response(210)
#     sql_CHECK_STATUS_ID = ProjectSqlMap.CHECK_STATUS_ID
#     CHECK_STATUS_ID = mysql_tools.select_one(sql_CHECK_STATUS_ID)
#     params["status_id"] = CHECK_STATUS_ID["status_id"]
#     sql_mysql_tools = ProjectSqlMap.FIND_NAME.format(**{"user_id": params["reciverlist_id"]})
#     res_reciverlist = mysql_tools.select_one(sql_mysql_tools)
#     params["reciverlist"] = res_reciverlist["real_name"]
#     sql = ProjectSqlMap.TASK_ADD1.format(**params)
#     mysql_tools.execute_sql(sql)
#     task_id = int(mysql_tools._conn.insert_id())
#     mysql_tools.commit_sql()
#     sql = ProjectSqlMap.TASK_USER_ADD.format(
#         **{"status_id": params["status_id"], "task_id": task_id, "task_recive_user_id": params["reciverlist_id"]})
#     mysql_tools.execute_sql(sql)
#     id = int(mysql_tools._conn.insert_id())
#     mysql_tools.commit_sql()
#     return success_response({"task_id": id})


def project_circle_add(params):
    dict = {
        "user_id": "user_id",
        "report_content": "report_content",
        "project_id": "project_id",
    }
    params = get_params(params, dict)
    if isinstance(params, JsonResponse):
        return params
    # for key, val in params.items():
    #     if val is None:
    #         return err_response(210)
    sql = ProjectSqlMap.project_circle_add.format(**params)
    mysql_tools.execute_sql(sql)
    id = mysql_tools.select_one(ProjectSqlMap.GET_ID).get("id")
    return success_response({"daily_report_id": id})


def project_circle_list(params):
    dict = {
        "user_id": "user_id",
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str_circle": "query_str",
        "project_id": "project_id"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # if not params["user_id"]:
    #     return err_response(210)
    sql = add_filter(ProjectSqlMap.project_circle_list, params, ["query_str_circle", "project_id"],
                     **ProjectSqlMap.FILTER_PARAMS)
    sql += " order by t1.publish_time desc"
    sql = sql.format(**params)
    result = mysql_tools.select_all(sql)
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        res["publish_time"] = str(res["publish_time"])
        res.pop("publish_user_id")
        res.pop("project_id")
    return success_response(result)


def project_list(params):
    dict = {
        "user_id": "user_id",
    }
    page_params = {
        "isall": "isAll",
        "size": "limit",
        "page": "page",
        "query_str": "query_str"
    }
    params = get_params(params, dict, page_params)
    if isinstance(params, JsonResponse):
        return params
    # if not params["user_id"]:
    #     return err_response(210)
    sql = add_filter(ProjectSqlMap.PROJECT_LIST, params, ["query_str"], **ProjectSqlMap.FILTER_PARAMS)
    sql += "order by t1.create_time desc"
    result = mysql_tools.select_all(sql.format(**params))
    if params.get("isall") != 1:
        result = paging_simple(result, params.get("page"), params.get("size"))
    if not result:
        return success_response([])
    for res in result:
        if res.get("create_time"):
            res["create_time"] = str(res.get("create_time"))
        else:
            res["create_time"] = None
        if res.get("project_state"):
            res["status_name"] = project_status.get(res.get("project_state"))
        if res.get("project_type"):
            res["type_name"] = project_type.get(res.get("project_type"))
    return success_response(result)


@format_response
def index(request):
    return com_views(request, {
        "my_project_message": my_project_message,
        "project_task": project_task,
        # "project_task_add": project_task_add,
        "project_circle_add": project_circle_add,
        "project_circle_list": project_circle_list,
        "project_list": project_list,
        "project_message": project_message
    })
